package cn.lili.controller.store;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.payment.kit.plugin.alipay.AliPayApi;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.entity.dos.StoreZft;
import cn.lili.modules.store.entity.vos.StoreDetailVO;
import cn.lili.modules.store.entity.vos.StoreZftSearchParams;
import cn.lili.modules.store.entity.vos.StoreZftVO;
import cn.lili.modules.store.service.StoreDetailService;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.store.service.StoreZftService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.response.AntMerchantExpandIndirectZftSimplecreateResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 店铺直付通管理接口
 *
 * @author Bulbasaur
 * @since 2022-08-09 14:55:49
 */
@SuppressWarnings("DuplicatedCode")
@Api(tags = "管理端,店铺直付通管理接口")
@RestController
@RequestMapping("/manager/store/zft")
public class StoreZftManagerController {

    /**
     * 店铺直付通
     */
    @Autowired
    private StoreZftService storeZftService;
    /**
     * 店铺详情
     */
    @Autowired
    private StoreDetailService storeDetailService;
    /**
     * 店铺
     */
    @Autowired
    private StoreService storeService;

    @ApiOperation(value = "获取店铺分页列表")
    @GetMapping("/storeList")
    public ResultMessage<List<Store>> getAllStore(@RequestParam(required = false) String keyword) {
        QueryWrapper<Store> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotEmpty(keyword)) {
            queryWrapper.like("store_name", keyword)
                    .or().eq("id", keyword);
        }

        return ResultUtil.data(storeService.list(queryWrapper));
    }

    @ApiOperation(value = "获取店铺直付通分页列表")
    @GetMapping
    public ResultMessage<IPage<StoreZftVO>> getByPage(StoreZftSearchParams entity, PageVO page) {
        return ResultUtil.data(storeZftService.findByConditionPage(entity, page));
    }

    @ApiOperation(value = "获取店铺详情")
    @ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "path", dataType = "String")
    @GetMapping(value = "/store/detail/{storeId}")
    public ResultMessage<StoreDetailVO> shopDetail(@PathVariable String storeId) {
        return ResultUtil.data(storeDetailService.getStoreDetailVO(storeId));
    }

    @ApiOperation(value = "获取店铺直付通详情")
    @ApiImplicitParam(name = "storeId", value = "店铺ID", required = true, paramType = "path", dataType = "String")
    @GetMapping(value = "/detail/{id}")
    public ResultMessage<StoreZft> detail(@PathVariable String id) {
        return ResultUtil.data(storeZftService.getById(id));
    }

    @ApiOperation(value = "添加店铺直付通二级商户")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage<StoreZft> add(@Valid StoreZft storeZft, Boolean isSubmit) {
        if (storeZftService.getByStoreId(storeZft.getStoreId()) == null) {
            JSONObject bizContent = JSON.parseObject(storeZft.getBizContent());
            bizContent.put("alipay_logon_id", bizContent.getString("binding_alipay_logon_id"));

            storeZft.setBizContent(bizContent.toJSONString());
            storeZft.setExternalId(storeZft.getStoreId());
            if (BooleanUtils.isNotTrue(isSubmit)) {
                storeZft.setStatus("0");
            } else {
                storeZft.setStatus("031");
                AntMerchantExpandIndirectZftSimplecreateResponse response = null;
                try {
                    response = AliPayApi.zftSimpleCreate(storeZft.getBizContent());
                    if (response.isSuccess()) {
                        storeZft.setOrderId(response.getOrderId());
                    } else {
                        throw new ServiceException(response.getMsg() + "：" + response.getSubMsg());
                    }
                } catch (AlipayApiException e) {
                    throw new ServiceException(ResultCode.ERROR, e.getMessage());
                }
            }
            boolean result = storeZftService.save(storeZft);
            if (result) {
                return ResultUtil.data(storeZft);
            } else {
                return ResultUtil.error(-1, "执行失败");
            }
        } else {
            return ResultUtil.error(-1, "这个店铺已经进件，不能重复进件");
        }
    }

    @ApiOperation(value = "编辑店铺直付通二级商户")
    @ApiImplicitParam(name = "id", value = "店铺ID", required = true, paramType = "path", dataType = "String")
    @PutMapping(value = "/edit/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage<StoreZft> edit(@PathVariable String id, @Valid StoreZft storeZft, Boolean isSubmit) {
        StoreZft zft = storeZftService.getById(id);
        if (zft == null) {
            return ResultUtil.error(-1, "执行失败");
        }
        JSONObject bizContent = JSON.parseObject(storeZft.getBizContent());
        bizContent.put("alipay_logon_id", bizContent.getString("binding_alipay_logon_id"));

        zft.setBizContent(bizContent.toJSONString());
        if (isSubmit && !"031".equals(storeZft.getStatus())) {
            AntMerchantExpandIndirectZftSimplecreateResponse response;
            try {
                response = AliPayApi.zftSimpleCreate(storeZft.getBizContent());
                if (response.isSuccess()) {
                    storeZft.setOrderId(response.getOrderId());
                } else {
                    throw new ServiceException(response.getMsg() + "：" + response.getSubMsg());
                }
            } catch (AlipayApiException e) {
                throw new ServiceException(ResultCode.ERROR, e.getMessage());
            }
        }
        storeZftService.updateById(zft);
        return ResultUtil.data(zft);
    }

    @ApiOperation(value = "编辑店铺直付通二级商户结算规则")
    @ApiImplicitParam(name = "id", value = "店铺ID", required = true, paramType = "path", dataType = "String")
    @PutMapping(value = "/editSettleRule/{id}")
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage<StoreZft> editSettleRule(@PathVariable String id, @Valid StoreZft storeZft) {
        StoreZft zft = storeZftService.getById(id);
        if (zft == null) {
            return ResultUtil.error(-1, "执行失败");
        }
        JSONObject bizContent = JSON.parseObject(storeZft.getBizContent());
        bizContent.put("alipay_logon_id", bizContent.getString("binding_alipay_logon_id"));

        zft.setBizContent(bizContent.toJSONString());
//        AntMerchantExpandIndirectZftSettlementmodifyModel model=new AntMerchantExpandIndirectZftSettlementmodifyModel();
//        model.setSmid(zft.getSmid());
//        model.set
//        AliPayApi.zftSettlementModify()
        storeZftService.updateById(zft);
        return ResultUtil.data(zft);
    }
}

